package birdsong.dummy;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;

import FollowME.ServerToClientMessage;

/**
 * A Thread class to manage the message received from the server.
 * 
 * @author Fernando Pereira, Marcos Martins
 * @version 2.0
 */
public class ServerHandler extends Thread {

	private Socket socket;
	private ObjectInputStream ois;

	private LinkedBlockingQueue<ServerToClientMessage> receivedMessages;

	/**
	 * 
	 * Constructor for a new {@link ServerHandler} thread.
	 * 
	 * @param socket
	 *            - Socket for serverHandler.
	 * @param receivedMessages
	 *            - A list of messages received from the server.
	 * 
	 */
	public ServerHandler(Socket socket,
			LinkedBlockingQueue<ServerToClientMessage> receivedMessages) {
		this.socket = socket;
		this.receivedMessages = receivedMessages;
	}

	/**
	 * The thread starts here and receives a message from the server. Then the
	 * server sends it to the client.
	 */
	@Override
	public void run() {
		try {
			ois = new ObjectInputStream(socket.getInputStream());
			while (socket.isConnected()) {
				receivedMessages.put((ServerToClientMessage) ois.readObject());
			}
		} catch (ClassNotFoundException e) {
			System.err
					.println("ERROR -  Message class - Server didn't received it");
		} catch (IOException e) {
			System.err.println("ERROR - ObjectInputStream");
		} catch (InterruptedException e) {
			System.err.println("ERROR - Put new messagem on list");
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				System.out.println("ERROR - Closing Socket");
			}
		}
	}
}
